#!/bin/bash
# 通用 Fail2Ban 安装与启用脚本
# 支持 RHEL 系 (CentOS / AlmaLinux / Rocky) 和 Debian 系 (Debian / Ubuntu)

echo "=== Fail2Ban 安装与启用脚本 ==="

# 必须 root 权限
if [ "$EUID" -ne 0 ]; then
    echo "❌ 请用 root 权限运行此脚本"
    exit 1
fi

# 检测系统类型
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS_ID=$ID
    OS_VER=$VERSION_ID
    echo "检测到系统：$NAME $VERSION"
else
    echo "❌ 无法检测系统类型"
    exit 1
fi

# 安装 Fail2Ban
if [[ "$OS_ID" =~ (centos|almalinux|rocky|rhel) ]]; then
    echo "📦 安装 Fail2Ban (RHEL 系)..."
    yum install -y epel-release
    yum install -y fail2ban fail2ban-firewalld || yum install -y fail2ban
elif [[ "$OS_ID" =~ (debian|ubuntu) ]]; then
    echo "📦 安装 Fail2Ban (Debian 系)..."
    apt update
    apt install -y fail2ban
else
    echo "❌ 暂不支持此系统"
    exit 1
fi

# 配置 Fail2Ban
JAIL_LOCAL="/etc/fail2ban/jail.local"
cat > "$JAIL_LOCAL" <<EOF
[sshd]
enabled = true
port    = ssh
filter  = sshd
logpath = /var/log/secure
maxretry = 5
findtime = 600
bantime = 3600
EOF

# 针对 Debian/Ubuntu 调整日志路径
if [[ "$OS_ID" =~ (debian|ubuntu) ]]; then
    sed -i 's|/var/log/secure|/var/log/auth.log|' "$JAIL_LOCAL"
fi

# 启用并启动 Fail2Ban
systemctl enable --now fail2ban
systemctl restart fail2ban

# 检查状态
systemctl status fail2ban --no-pager

echo "✅ Fail2Ban 已安装并启用"
echo "   - 最大尝试次数: 5 次"
echo "   - 检测时间窗口: 10 分钟"
echo "   - 封禁时长: 1 小时"
echo "💡 查看被封禁的 IP: fail2ban-client status sshd"